"""This module provides mydouyn"""
import json
import os
import time
import platform
import datetime
from playwright.sync_api import sync_playwright
from playwright.sync_api import Page
from auto.sleep.data import go_to_sleep
from auto.sleep.data import get_pitcute
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
######################global########################
LOG_FORMAT = "[%(asctime)s][%(levelname)s][%(filename)s:%(funcName)s:%(lineno)d] %(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
TOTAL_WORK_TIME = 180
TOTAL_COUNT= 0
one_work_time =30
#STEPS = 10
STEPS = 10
TOTAL_WORK_TIME_COUNT = 0
########################################################################
class CBiBiZh:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """
    def __init__(self,cookies_path: str, login_url: str, post_url: str):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.post_url = post_url
        # playwright 部分
        self.browser = None
        self.context = None
        print("create CBiBiZh")

    def __del__(self):
        print("CBiBiZh is being destroyed")

    def login_or_restore_cookies(self) -> Page:
        """
          登录
        """
        user_agent ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.21 Safari/537.36"


        if platform.system() == "Linux":
            user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        elif platform.system() == "Linux":
            user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
        
        self.context = self.browser.new_context(user_agent=user_agent)
        self.context.clear_cookies()
        page = self.context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            print("load cookies")
            # 从文件中加载 cookies
            with open(self.cookies_path, 'r',encoding='utf-8') as f:
                cookies = json.load(f)
            self.context.add_cookies(cookies)
            time.sleep(3)
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(60)
            cookies = page.context.cookies()
            with open(self.cookies_path, 'w',encoding='utf-8') as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page
    ###########################################
    def msg_up_load(self, page: Page, picture_path_list,habit_name:str, habit_detail:str):
        """
         发布微头条
        """
        page.goto(self.post_url)
        page.wait_for_timeout(5000)
        print(f"open  {self.post_url}")

        msg = habit_name + " "
        msg += habit_detail
        msg = msg.replace("\n", "")
        msg = msg.replace("\r", "")
        # Allows locating input elements by the placeholder text.
        page.get_by_placeholder("有什么想和大家分享的？").fill(msg)
        page.wait_for_timeout(5000)
        # playwright codegen https://weibo.com/
     
  
        #page.locator(".bili-dyn-publishing__action.launcher").click()
        #page.get_by_text("发布", exact=True).click()
        
        print("发送")
        page.wait_for_timeout(5000)
        page.get_by_text("发布", exact=True).click()
        try: 
            with self.context.expect_page() as popup_info:
                page.get_by_text("确认并发送", exact=True).click()
         #       
         #   new_page = popup_info.value
         #   new_page.wait_for_load_state()

          #   new_page.get_by_role("button", name="确认删除").click()
           #  page.wait_for_timeout(2000)
             ##page.on("dialog", lambda dialog: dialog.accept())
        except Exception as err:
             print(f"Unexpected {err=}, {type(err)=}")
        page.wait_for_timeout(5000)
        

###############################################################

def interface_auo_upload_msg_bibil(file_path_list:str,habit_name :str,habit_detail :str):
    """
      对外调用接口
    """
    print("interface_auo_upload_zhihu_small")
    sys = platform.system()
    login_url = "https://t.bilibili.com/?spm_id_from=333.999.0.0"
    upload_picture_url = "https://t.bilibili.com/?spm_id_from=333.999.0.0"
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\bb_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/bb_small.json"
    else:
        cookies_path = r"/root/bin/bb_small.json"
    autoupload = CBiBiZh(cookies_path, login_url, upload_picture_url)
    with sync_playwright() as playwright:
        display_headless = False
        sys = platform.system()
        if sys == "Linux":
            display_headless = True
            browser = playwright.chromium.launch(headless=display_headless)
        else:
            browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
        autoupload.browser = browser
        login_page = autoupload.login_or_restore_cookies()
        # 发布微头条
        try:
            autoupload.msg_up_load(login_page, file_path_list, habit_name,habit_detail)
            autoupload.browser.close()
        except Exception as err:
            print(f"Unexpected {err=}, {type(err)=}")

###################################################
def future_for_sleep():
    """
      每天写50字产品理解输出，10行代码
    """
    habit_detail = go_to_sleep.interface_go_to_sleep()
    random_images = get_pitcute.interface_get_three_pic()
    habit_name = "21点远离手机提醒"
    # 格式化为 年-月-日
    formatted_date = datetime.datetime.now().strftime('%Y-%m-%d')
    habit_name = formatted_date + " " + habit_name

    try:
        interface_auo_upload_msg_bibil(random_images, habit_name, habit_detail)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
if __name__ == '__main__':
    future_for_sleep()
    job_defaults = {
        'coalesce': False,
        'max_instances': 1
    }
    # 调度器组件
    backsched = BlockingScheduler(job_defaults=job_defaults, timezone='Asia/Shanghai')
    # future_for_sleep callable函数 习惯养成--早睡早起
    # crontab 是 Linux 系统中用于设置周期性被执行的指令的命令
    # 0 0 * * *	每天的午夜（0 点）执行一次
    backsched.add_job(future_for_sleep, CronTrigger.from_crontab("0 21 * * *"), id="get_up")
    backsched.start()
    # playwright codegen https://www.bilibili.com/
